import axios from 'axios';
import router from '../router'
import { message } from 'ant-design-vue';
// 创建实例
let instance = axios.create({
  timeout: 60000,
  baseURL: process.env.API,
  withCredentials: true, // 允许跨域携带cookie
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    // 'Access-Token': localStorage.getItem('token')
  }
});
// 添加请求拦截器，在请求头中加token
instance.interceptors.request.use(
  config => {
    //判断token是否存在
    if (localStorage.getItem('token')) {
      // 在请求头中添加token
      config.headers['Access-Token'] = localStorage.getItem('token');
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });

// 添加响应拦截器(data)
instance.interceptors.response.use(response => {
    //下载文件异常处理
    if (response.data.type== 'application/json'&&response.config.responseType== 'blob') {
      const reader = new FileReader();
      reader.addEventListener('loadend', function (e) {
        let text = e.target.result;
        let parse = JSON.parse(text);
        if (parse.result === 'exception') {
          message.error(parse.message);
        } else if (parse.result === 'failed') {
          message.warn(parse.message);
        }
      });
      reader.readAsText(response.data);
    }
    //异常提示
    if (response.data.result == 'exception') {
      message.error(response.data.message);
    }else if (response.data.result == 'failed') {
      //警告提示
      if(!response.data.data) {
        message.warn(response.data.message);
      }
    }

  return response;

}, error => {
  // 对响应错误做点什么
  if (error.response!=undefined&&error.response.status === 401) {
    //没登录跳登录页
    let href = window.location.href;
    let url = window.location.href.substr(href.lastIndexOf('/'));
    if (url !== '/') {
      router.push('/');
    }
  }
  if (error.response!=undefined&&error.response.status === 403) {
    //没权限
    message.warn(error.response.data.message);
  }
  return Promise.reject(error);
});

// 登录请求方法
const loginreq = (method, url, params) => {
  return instance({
    method: method,
    url: url,
    header: {
      'Content-Type': 'application/x-www-form-urlencoded',
      // 'Access-Token': localStorage.getItem('token')
    },
    data: params,
    traditional: true,
    transformRequest: [
      function (data) {
        let ret = '';
        for (let it in data) {
          ret +=
            encodeURIComponent(it) +
            '=' +
            encodeURIComponent(data[it]) +
            '&';
        }
        return ret;
      }
    ]
  })
    .then(res => res.data);
};
// 通用公用方法
// src/api/axiosFun.js

// 通用公用方法
const req = (method, url, params, config = {}) => {
  // 合并配置项，优先使用传入的 headers
  const finalConfig = {
    ...{
      // 默认配置
      headers: {}
    },
    ...config,
    headers: {
      ...{
        // 默认 Content-Type
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      ...(config.headers || {})
    }
  };

  return instance({
    method: method,
    url: url,
    data: params,

    // 如果是 FormData，不进行参数转换
    transformRequest: (params instanceof FormData)
      ? []
      : [
        function (data) {
          let ret = '';
          for (let it in data) {
            ret +=
              encodeURIComponent(it) +
              '=' +
              encodeURIComponent(data[it]) +
              '&';
          }
          return ret;
        }
      ],
  }).then(res => {
    if (config.returnFullResponse) {
      return res;
    }
    return res.data;
  });
};
// 文件下载方法
const fileDownload = (method, url, params) => {
  return instance({
    method: method,
    url: url,
    data: params,
    traditional: true,
    responseType: 'blob',
    transformRequest: [
      function (data) {
        let ret = '';
        for (let it in data) {
          ret +=
            encodeURIComponent(it) +
            '=' +
            encodeURIComponent(data[it]) +
            '&';
        }
        return ret;
      }
    ]
  }).then(res => res.data);
};

export {
  loginreq,
  req,
  fileDownload
};
